package com.gaohc.controller.system;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.gaohc.common.constant.Constants;
import com.gaohc.common.core.domain.AjaxJson;
import com.gaohc.common.core.domain.entity.SysUser;
import com.gaohc.common.core.domain.model.LoginBody;
import com.gaohc.common.core.domain.entity.SysMenu;
import com.gaohc.framework.web.service.SysLoginService;
import com.gaohc.framework.web.service.SysPermissionService;
import com.gaohc.system.sysmenu.ISysMenuService;
import com.gaohc.system.sysuser.ISysUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Resource
    private SysLoginService loginService;
    @Resource
    private ISysUserService userService;
    @Resource
    private SysPermissionService permissionService;
    @Resource
    private ISysMenuService menuService;
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxJson login(@RequestBody LoginBody loginBody)
    {
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        Map<String, String> map = new HashMap<>();
        map.put(Constants.TOKEN, token);
        return AjaxJson.getSuccessData(map);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @SaCheckLogin
    @GetMapping("getInfo")
    public AjaxJson getInfo()
    {
        Long userId = Long.parseLong(StpUtil.getLoginId().toString());
        SysUser user = userService.getUserInfoById(userId);

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return AjaxJson.getSuccessData(map);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @SaCheckLogin
    @GetMapping("getRouters")
    public AjaxJson getRouters()
    {
        Long userId = Long.parseLong(StpUtil.getLoginId().toString());
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxJson.getSuccessData(menuService.buildMenus(menus));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @PostMapping("logout")
    public AjaxJson logout() {
        StpUtil.logout();
        return AjaxJson.getSuccess();
    }



}
